package com.server;

import com.model.Exam;
import com.model.Student;
import com.model.StudentMessage;
import com.model.UserMessage;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * 服务器端对考题系统的操作类
 */
public class ExamSystemOperation {
    private List<Exam> exams = new ArrayList<>();
    private StudentSystemOperation studentSystemOperation = new StudentSystemOperation();
    private StudentMessage studentMessage;

    public ExamSystemOperation() {
        serverReadExamFile();
    }

    public List<Exam> getExams() {
        return exams;
    }

    public void setExams(List<Exam> exams) {
        this.exams = exams;
    }

    /**
     * 服务器端接收客户端发来的增加考题请求，并增加考题，返回是否添加成功
     * @param exam
     * @return
     */
    public boolean add(Exam exam){
        // 当系统中无考题时，直接添加
        if (exams == null || exams.size() == 0){
            exams.add(exam);
        }
        // 若有考题时，则需要通过遍历所有考题的id，若id相同则追加到尾部，更新id
        else {
            // 利用迭代器遍历，否则会出错
            ListIterator<Exam> listIterator = exams.listIterator();
            while (listIterator.hasNext()){
                Exam cur_exam = listIterator.next();
                // 判断添加考题id是否与系统中已有考题id相同,若相同，则提示已经存在
                if (cur_exam.getId() == exam.getId()){
                    exam.setId(exams.size()+1);
                }
            }
            // 添加到最后
            exams.add(exam);
        }
        serverSaveExamFile(exams);
        return true;
    }

    /**
     * 服务器端删除考题信息，并返回是否删除成功
     * @param id
     * @return
     */
    public boolean delete(int id){
        // 遍历考题信息，删除id的考题
        ListIterator<Exam> listIterator = exams.listIterator();
        while (listIterator.hasNext()){
            Exam cur_exam = listIterator.next();
            if (cur_exam.getId() == id){
                listIterator.remove();
                serverSaveExamFile(exams);
                return true;
            }
        }
        return false;
    }

    /**
     * 服务器端修改考题信息，默认id不能被修改，并返回是否修改成功
     * @param exam
     * @return
     */
    public boolean modify(Exam exam){
        // 遍历考题信息，修改对应id的考题信息
        ListIterator<Exam> listIterator = exams.listIterator();
        while (listIterator.hasNext()){
            Exam cur_exam = listIterator.next();
            if (cur_exam.getId() == exam.getId()){
                cur_exam.setQuestion(exam.getQuestion());
                cur_exam.setAnswers(exam.getAnswers());
                cur_exam.setRightAnswer(exam.getRightAnswer());
                serverSaveExamFile(exams);
                return true;
            }
        }
        return false;
    }

    /**
     * 服务器端查找考题信息，根据题干信息关键字查找，若存在返回该考题，否则返回null
     * @param keyWords
     * @return
     */
    public Exam find(String keyWords){
        ListIterator<Exam> listIterator = exams.listIterator();
        while (listIterator.hasNext()){
            Exam cur_exam = listIterator.next();
            if (cur_exam.getQuestion().contains(keyWords)){
                return cur_exam;
            }
        }
        return null;
    }

    /**
     * 服务器端返回所有考题，若无则返回null
     * @return
     */
    public List<Exam> showAll(){
        if (exams.size() == 0){
            return null;
        }
        else {
            return getExams();
        }
    }

    /**
     * 服务器端读取本地考题文件
     */
    public void serverReadExamFile(){
        File file = new File("./ExamSystemServer/src/com/exams.txt");
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            // 读取服务器上的文件
            fileInputStream = new FileInputStream(file);
            objectInputStream = new ObjectInputStream(fileInputStream);
            List<Exam> exams = (List<Exam>) objectInputStream.readObject();
            this.setExams(exams);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectInputStream != null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 服务器端将考题重新写入到本地文件
     * @param exams
     */
    public void serverSaveExamFile(List<Exam> exams){
        File file = new File("./ExamSystemServer/src/com/exams.txt");
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            // 写入服务器本地中
            fileOutputStream = new FileOutputStream(file);
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(exams);
            objectOutputStream.flush();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (objectOutputStream != null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将客户端上传的文件导入到服务器
     * @param file
     */
    public boolean importExam(File file){
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            objectInputStream = new ObjectInputStream(fileInputStream);
            List<Exam> importExam = (ArrayList<Exam>) objectInputStream.readObject();
            // 逐条扫描导入的考题，逐条添加
            Iterator<Exam> iterator = importExam.listIterator();
            while (iterator.hasNext()){
                add(iterator.next());
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        }finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
    }

    /**
     * 服务器端返回所有考题、查询成绩、导出成绩
     */
    public StudentMessage sendExamOrScore(UserMessage userMessage){
        List<Student> students = studentSystemOperation.getStudents();
        if (userMessage.getMessage().equals("startExam")){
            for (Student student : students){
                if (student.getUserName().equals(userMessage.getUser().getUserName()) && student.getPassWord().equals(userMessage.getUser().getPassWord())){
                    student.setExaming(true);
                    student.setExams(this.getExams());
                    studentMessage = new StudentMessage("successStartExam",student);
                    break;
                }
            }
        }else if (userMessage.getMessage().equals("queryScore")){
            for (Student student : students){
                if (student.getUserName().equals(userMessage.getUser().getUserName()) && student.getPassWord().equals(userMessage.getUser().getPassWord())){
                    studentMessage = new StudentMessage("successQueryScore",student);
                    studentMessage.getStudent().setExaming(false);
                    studentMessage.getStudent().setExams(null);
                    break;
                }
            }
        }else if (userMessage.getMessage().equals("ExportScore")){
            for (Student student : students){
                if (student.getUserName().equals(userMessage.getUser().getUserName()) && student.getPassWord().equals(userMessage.getUser().getPassWord())){
                    studentMessage = new StudentMessage("successExportScore",student);
                    studentMessage.getStudent().setExaming(false);
                    studentMessage.getStudent().setExams(null);
                    break;
                }
            }
        }
        studentSystemOperation.serverSaveStudentFile(students);
        return studentMessage;
    }

    /**
     * 服务器修改成绩
     */
    public void serverModifyScore(StudentMessage studentMessage,Integer score){
        List<Student> students = studentSystemOperation.getStudents();
        for (Student student : students){
            if (student.getId().equals(studentMessage.getStudent().getId())){
                student.setScore(score);
                //System.out.println(student.toString());
                break;
            }
        }
        studentSystemOperation.serverSaveStudentFile(students);
    }
}
